package cn.hc.tool.concurrent.conf;

import cn.hc.tool.concurrent.util.HcParallelUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/10/17 20:58
 */
@Configuration
public class HcParallelAutoConfiguration {

    @Value("${hc.parallel.corePoolSize:5}")
    private Integer corePoolSize;
    @Value("${hc.parallel.maxPoolSize:5}")
    private Integer maxPoolSize;
    @Value("${hc.parallel.keepAliveSeconds:5}")
    private Integer keepAliveSeconds;
    @Value("${hc.parallel.queueCapacity:20}")
    private Integer queueCapacity;

    @Bean
    @ConditionalOnMissingBean(HcParallelUtil.class)
    public HcParallelUtil hcParallelUtil() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
                keepAliveSeconds, TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueCapacity), r -> {
            Thread thread = new Thread(r);
            thread.setName("HcParallelUtil-" + thread.hashCode());
            return thread;
        }, new ThreadPoolExecutor.CallerRunsPolicy());
        return new HcParallelUtil(executor);
    }
}
